#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->sendButton->setEnabled(false);
    ui->listenButton->setEnabled(false);
    ui->relistenButton->setEnabled(false);
    ui->sendButton->setEnabled(false);
}

MainWindow::~MainWindow()
{
    if(fd_com >= 0)
        ::close(fd_com);
    qDebug()<<"fd_com closed";
    delete ui;
}

void MainWindow::on_exitButton_clicked()
{
    this->close();//close equals click x
}

void MainWindow::on_sendButton_clicked()
{
    //uart test
    memset(buff, 0, BUFFER_SIZE);

    if(ui->lineEdit->text() != "")
    {
        strcpy(buff, ui->lineEdit->text().toLatin1());
        write(fd_com, buff, strlen(buff));
    }
}

void MainWindow::receiverbuff(QString data)
{
    re->enStopFlag();
    static int count=0;
    count++;
    ui->lineEdit->setText(QString::number(count));
    ui->textEdit_2->setText(data);
    int ll=sizeof(data);
    QString revData;
    ui->lineEdit_2->setText(QString::number(ll));
    for(int i=0;i<data.count();i++)
    {
        QString s;
        s.sprintf("0x%02x, ",data.at(i));
        revData+=s;
        s.clear();
    }
    ui->textEdit->setText(revData);
    revData.clear();
    re->disStopFlag();
}

void MainWindow::on_listenButton_clicked()
{
    re = new ReceiveThread;
    ui->listenButton->setEnabled(false);
    ui->relistenButton->setEnabled(true);
    connect(re, SIGNAL(sendbuff(QString)), this, SLOT(receiverbuff(QString)));
    re->fd = fd_com;
    re->start();
}

void MainWindow::on_encomButton_clicked()
{
    ui->encomButton->setEnabled(false);

    // /dev/tq2440_serial0
    // /dev/ttyUSB0

    if(ui->comSelectcomboBox->currentIndex() == 0)
        fd_com = open_port("/dev/tq2440_serial0");
    else if (ui->comSelectcomboBox->currentIndex() == 1)
        fd_com = open_port("/dev/ttyUSB0");
    else exit(1);

    if( fd_com < 0 )
    {
        perror("open_port");
        return ;
    }

    if(set_com_config(fd_com, ui->baudcomboBox->currentText().toInt(), 8, 'n', 1) < 0)
    {
        perror("set_com_config");
        return ;
    }
    ui->listenButton->setEnabled(true);
    ui->sendButton->setEnabled(true);
    ui->sendButton->setEnabled(true);
    ui->comSelectcomboBox->setEnabled(false);
}

void MainWindow::on_relistenButton_clicked()
{
    re->enStopFlag();
    ui->relistenButton->setEnabled(false);
    ui->listenButton->setEnabled(true);
    re->terminate();
}

void MainWindow::on_baudcomboBox_currentIndexChanged(QString )
{
    qDebug()<<"Now baudrate is:"<<ui->baudcomboBox->currentText().toInt();
    re->enBaudChanged_flag();
    if(ui->encomButton->isEnabled())
        return ;
    if(set_com_config(fd_com, ui->baudcomboBox->currentText().toInt(), 8, 'n', 1) < 0)
    {
        perror("set_com_config");
        return ;
    }
}
